package com.xr.handle;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Arnold Yand
 * @summary 替换掉框架的ResponseBody包装类
 * @time 2018/4/7 11:59
 */
public class ResponseBodyWrapFactoryBean implements InitializingBean {

  @Autowired
  private RequestMappingHandlerAdapter adapter;

  @Override
  public void afterPropertiesSet() throws Exception {
    List<HandlerMethodReturnValueHandler> returnValueHandlers = adapter.getReturnValueHandlers();
    List<HandlerMethodReturnValueHandler> handlers = new ArrayList<>(returnValueHandlers);
    decorateHandlers(handlers);
    adapter.setReturnValueHandlers(handlers);
  }

  private void decorateHandlers(List<HandlerMethodReturnValueHandler> handlers) {
    for (HandlerMethodReturnValueHandler handler : handlers) {
      if (handler instanceof RequestResponseBodyMethodProcessor) {

        // 替换掉框架的ResponseBody包装类
        ResponseBodyWrapHandle decorator = new ResponseBodyWrapHandle(handler);

        int index = handlers.indexOf(handler);
        handlers.set(index, decorator);
        break;
      }
    }
  }
}
